package udp
{
	import flash.events.DatagramSocketDataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.DatagramSocket;
	import flash.utils.ByteArray;
	
	import k3.event.KEvent;
	
	import org.tuio.*;
	import org.tuio.osc.OSCBundle;

	//import ru.valyard.osc.*;
	//import ru.valyard.osc.data.OSCMessage;
	//import ru.valyard.osc.data.OSCPacket;
	
	public class UdpManager extends EventDispatcher
	{
		private  static var datagramSocket:DatagramSocket = new DatagramSocket();
		private static var ip:String;
		private static var port:uint;
		public static const SOCKET_DATA:String="dataRecive";
		public function UdpManager()
		{
			
		}
		
		public static function init(_ip:String,_port:uint)
		{
			ip=_ip;
			port=_port;
			datagramSocket.bind(port, ip );
			datagramSocket.addEventListener( DatagramSocketDataEvent.DATA, dataReceived );
			datagramSocket.receive();
		}
		
		
		private static function dataReceived( event:DatagramSocketDataEvent ):void
		{
			//Read the data from the datagram
			
			
			var packet:ByteArray = new ByteArray();
			packet.writeBytes(event.data);
			packet.position = 0;
			var bundle:OSCBundle=new OSCBundle(packet);
			trace(bundle.getPacketInfo());
//			var factory:OSCMessageFactory=new OSCMessageFactory();
//			var pack:OSCPacket=factory.readOSCPacket(packet);
//			var length:uint=pack.length;
//			for(var i:uint=0;i<length;i++)
//			{
//				var message:OSCMessage=pack[i] as OSCMessage;
//				trace(i+" |"+ message);
//			}
			//GlobalValue.whiteTxt("Received from " + event.srcAddress + ":" + event.srcPort + "> " + str );
			//this.dispatchEvent(new KEvent("dataRecive",str));
		}
		
		public static function send(str:String,targetIp:String,targetPort:uint):void
		{
			var data:ByteArray = new ByteArray();
			data.writeUTFBytes( str );
			//GlobalValue.whiteTxt( "ready Sent message  :" +str +" to " + targetIp + ":" + targetPort);
			//Send a datagram to the target
			try
			{
				datagramSocket.send( data, 0, 0,targetIp,targetPort); 
				//GlobalValue.greenTxt( "Sent message to " + targetIp + ":" + targetPort+" success" );
			}
			catch ( error:Error )
			{
				//GlobalValue.redTxt("UdpManager port:"+datagramSocket.localPort+" have error:"+ error.message );
			}
		}
		
		public static function gc():void
		{
			if( datagramSocket.bound ) 
			{
				datagramSocket.close();
				datagramSocket=null;
			}
		}
	}
}